﻿using Nop.Core.Domain.Customers;
using Nop.Core.Domain.XJ;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.XJ;
using Nop.Web.Framework.Security;
using Nop.Web.Models.Home;
using Nop.Web.Models.XJ;
using System;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Web.Controllers
{
	public class InspectionController : Controller
	{
		#region Fields
		private readonly IDepartmentService _departmentService;
		private readonly ICustomerService _customerService;
		private readonly IFilesService _filesService;
		private readonly IPictureService _pictureService;
		private readonly IMessageService _messageService;
		private readonly ILogger _logger;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly IXJEquipmentCategoryService _xJEquipmentCategoryService;
		private readonly IXJEquipmentService _xJEquipmentService;
		private readonly IXJEquipmentStockService _xJEquipmentStockService;
		private readonly IXJInspectionService _xJInspectionService;
		private readonly IXJInspectionPlanService _xJInspectionPlanService;
		private readonly IXJMaintenanceService _xJMaintenanceService;
		private readonly IXJMaintenanceScheduleService _xJMaintenanceScheduleService;
		private readonly IXJMaintenanceCustomersService _xJMaintenanceCustomersService;
		private readonly IXJMaintenanceCommentService _xJMaintenanceCommentService;
		#endregion

		#region Ctor
		public InspectionController(
			IDepartmentService departmentService,
			ICustomerService customerService,
			IFilesService filesService,
			IPictureService pictureService,
			IMessageService messageService,
			ILogger logger,
			IGenericAttributeService genericAttributeService,
			IXJEquipmentCategoryService xJEquipmentCategoryService,
			IXJEquipmentService xJEquipmentService,
			IXJEquipmentStockService xJEquipmentStockService,
			IXJInspectionService xJInspectionService,
			IXJInspectionPlanService xJInspectionPlanService,
			IXJMaintenanceService xJMaintenanceService,
			IXJMaintenanceScheduleService xJMaintenanceScheduleService,
			IXJMaintenanceCustomersService xJMaintenanceCustomersService,
			IXJMaintenanceCommentService xJMaintenanceCommentService)
		{
			this._departmentService = departmentService;
			this._customerService = customerService;
			this._filesService = filesService;
			this._pictureService = pictureService;
			this._messageService = messageService;
			this._logger = logger;
			this._genericAttributeService = genericAttributeService;
			this._xJEquipmentCategoryService = xJEquipmentCategoryService;
			this._xJEquipmentService = xJEquipmentService;
			this._xJEquipmentStockService = xJEquipmentStockService;
			this._xJInspectionService = xJInspectionService;
			this._xJInspectionPlanService = xJInspectionPlanService;
			this._xJMaintenanceService = xJMaintenanceService;
			this._xJMaintenanceScheduleService = xJMaintenanceScheduleService;
			this._xJMaintenanceCustomersService = xJMaintenanceCustomersService;
			this._xJMaintenanceCommentService = xJMaintenanceCommentService;
		}
		#endregion

		#region Utilities

		#endregion

		/// <summary>
		/// 我的巡检记录
		/// </summary>
		/// <param name="customerId"></param>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult List(Customer customer, string name = "", int typeId = 0, int state = 0, int pageIndex = 0, int pageSize = 10)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var inspections = _xJInspectionService.GetMyInspections(
				customer: customer,
				name: name,
				typeId: typeId,
				pageIndex: pageIndex,
				pageSize: pageSize);
			return Json(new
			{
				result = true,
				model = inspections.Select(x =>
				{
					var item = new ListItemModel
					{
						Id = x.Id,
						Title = x.Comment,
						Label = x.CreatedOn.ToString("yyyy-MM-dd HH:mm"),
						Value = x.CustomerName
					};
					return item;
					//var inspection = new InspectionListItemModel
					//{
					//	Id = x.Id,
					//	TypeName = Enum.GetName(typeof(InspectionTypeEnum), x.TypeId),
					//	EquipmentName = x.EquipmentName,
					//	TeamName = x.TeamName,
					//	PersonName = x.PersonName,
					//	PlanOn = x.PlanOn.ToString("yyyy-MM-dd"),
					//	InspectionPersonName = x.InspectionPersonName,
					//	InspectionOn = x.InspectionOn.HasValue ? x.InspectionOn.Value.ToString("yyyy-MM-dd") : "",
					//	StateName = Enum.GetName(typeof(InspectionStateEnum), x.State)
					//};
					//return inspection;
				}),
				inspections.PageIndex,
				inspections.TotalPages
			});
		}

		[HttpPost]
		public JsonResult View(int inspectionId)
		{
			var model = new InspectionModel();
			var inspection = _xJInspectionService.GetXJInspectionById(inspectionId);
			if (null != inspection)
			{
				model.Id = inspection.Id;
				model.InspectionPlanId = inspection.Id;
				model.Comment = inspection.Comment;
				var plan = _xJInspectionPlanService.GetXJInspectionPlanById(inspection.InspectionPlanId);
				if (null != plan)
				{
					model.TypeName = Enum.GetName(typeof(InspectionTypeEnum), plan.TypeId);
					model.TeamName = _departmentService.GetNameById(plan.TeamId);
					if (plan.PersonId > 0)
					{
						model.PersonName = _customerService.GetNameById(plan.PersonId);
					}
				}

				var pictures = inspection.GetAttribute<string>("Pictures");
				if (!string.IsNullOrEmpty(pictures))
				{
					var pictureIds = pictures
						.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
						.Select(x => Convert.ToInt32(x))
						.ToArray();
					foreach (var p in pictureIds)
					{
						model.Pictures.Add(_pictureService.GetPictureUrl(p));
					}
				}
				model.CustomerId = inspection.CustomerId;
				model.CreatedOn = inspection.CreatedOn.ToString("yyyy-MM-dd");
			}
			return Json(new { resut = true, model });
		}

		/// <summary>
		/// 上报巡检记录
		/// </summary>
		/// <param name="customer"></param>
		/// <param name="planId">计划</param>
		/// <param name="comment">说明</param>
		/// <param name="selectedPictureIds"></param>
		/// <param name="bx">报修</param>
		/// <param name="placeId">巡检点</param>
		/// <param name="placeName"></param>
		/// <param name="categoryId">设备分类</param>
		/// <param name="categoryName"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult Add(Customer customer, int planId, string comment = "", string selectedPictureIds = null, bool bx = false, int categoryId = 0, int placeId = 0, string categoryName = null, string placeName = null)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			if (string.IsNullOrEmpty(comment) || comment.Length > 50)
				return Json(new { result = false, msg = "巡检说明为1~50字" });

			var plan = _xJInspectionPlanService.GetXJInspectionPlanById(planId);
			if (plan == null || plan.Deleted || !plan.Published)
				return Json(new { result = false, msg = "巡检计划无效" });

			var inspection = new XJInspection
			{
				InspectionPlanId = planId,
				Comment = comment,
				CustomerId = customer.Id,
				CustomerName = customer.TrueName,
				CreatedOn = DateTime.Now,
			};
			if (!_xJInspectionService.AllowInsert(inspection))
				return Json(new { result = false, msg = "巡检记录重复" });
			_xJInspectionService.InsertXJInspection(inspection);

			if (!string.IsNullOrEmpty(selectedPictureIds))
			{
				_genericAttributeService.SaveAttribute(inspection, "Pictures", selectedPictureIds);
			}

			if (bx)
			{
				var maintenance = new XJMaintenance
				{
					PNo = plan.PNo,
					SNo = _xJMaintenanceService.GenerateNo(),
					InspectionPlanId = planId,
					InspectionId = inspection.Id,
					CategoryId = categoryId,
					CategoryName = categoryName,
					PlaceId = placeId,
					PlaceName = placeName,
					Comment = comment,
					State = (int)MaintenanceStateEnum.待指派,
					CustomerId = customer.Id,
					CustomerName = customer.TrueName,
					DepartmentId = customer.DepartmentId,
					DepartmentName = customer.DepartmentName,
					CreatedOn = DateTime.Now
				};

				if (plan.MaintenanceTeamId > 0)
				{
					var team = _departmentService.GetDepartmentById(plan.MaintenanceTeamId);
					if (team != null)
					{
						// 是班组-->待维修
						if (team.PId > 0)
						{
							var depart = _departmentService.GetDepartmentById(team.PId);
							if (depart != null)
							{
								maintenance.ResponsibleDepartmentId = depart.Id;
								maintenance.ResponsibleDepartmentName = depart.Name;
							}
							maintenance.ResponsibleTeamId = team.Id;
							maintenance.ResponsibleTeamName = team.Name;
							maintenance.State = (int)MaintenanceStateEnum.待维修;
						}
						// 是部门-->待确认
						else
						{
							maintenance.ResponsibleDepartmentId = team.Id;
							maintenance.ResponsibleDepartmentName = team.Name;
							maintenance.State = (int)MaintenanceStateEnum.待确认;
						}
					}
				}

				if (plan.MaintenancePersonId > 0)
				{
					// 是维修人-->待维修
					var person = _customerService.GetCustomerById(plan.MaintenancePersonId);
					if (null != person && person.IsRepairman())
					{
						maintenance.ResponsiblePersonId = person.Id;
						maintenance.ResponsiblePersonName = person.TrueName;
						// 维修人
						_xJMaintenanceCustomersService.InsertXJMaintenanceCustomers(new XJMaintenanceCustomers { MaintenanceId = maintenance.Id, CustomerId = person.Id, CustomerName = person.TrueName });
					}
				}
				_xJMaintenanceService.InsertXJMaintenance(maintenance);

				if (!string.IsNullOrEmpty(selectedPictureIds))
				{
					_genericAttributeService.SaveAttribute(maintenance, "Pictures", selectedPictureIds);
				}

				if (maintenance.State == (int)MaintenanceStateEnum.待维修)
				{
					// 分配时新增维修时间表，截止时计算工时
					_xJMaintenanceScheduleService.NewSchedule(new XJMaintenanceSchedule
					{
						MaintenanceId = maintenance.Id,
						StartOn = DateTime.Now,
						StartCustomer = customer.TrueName,
					});
				}

				var mComment = new XJMaintenanceComment
				{
					MaintenanceId = maintenance.Id,
					TypeId = (int)MaintenanceCommentTypeEnum.维修申请,
					Comment = string.Format("报修-->{0}", comment),
					CustomerId = customer.Id,
					CreatedOn = DateTime.Now,
				};
				_xJMaintenanceCommentService.InsertXJMaintenanceComment(mComment);
			}

			// 生成漏检记录
			_xJInspectionPlanService.AddLoss(customer, plan);

			return Json(new { result = true, msg = "提交成功" });
		}
	}
}